/*
 * The MIT License (MIT)
 *
 * Copyright (c) 2014-2016 abel533@gmail.com
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 */

package tk.mybatis.mapper.entity;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Set;

import javax.persistence.Table;

import org.apache.ibatis.builder.IncompleteElementException;
import org.apache.ibatis.builder.MapperBuilderAssistant;
import org.apache.ibatis.builder.ResultMapResolver;
import org.apache.ibatis.mapping.Discriminator;
import org.apache.ibatis.mapping.ResultFlag;
import org.apache.ibatis.mapping.ResultMap;
import org.apache.ibatis.mapping.ResultMapping;
import org.apache.ibatis.session.Configuration;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import tk.mybatis.mapper.util.StringUtil;

/**
 * 数据库表
 *
 * @author liuzh
 */
public class EntityTable {
	protected static final Logger logger = LoggerFactory.getLogger(EntityTable.class);
    private String name;
    private String catalog;
    private String schema;
    private String orderByClause;
    private String baseSelect;
    //实体类 => 全部列属性
    private Set<EntityColumn> entityClassColumns;
    //实体类 => 主键信息
    private Set<EntityColumn> entityClassPKColumns;
    //实体类 => 一对一信息
    private Set<OneToOneEntity> entityTableOneToOnes;
    //实体类 => 一对多信息
    private Set<OneToManyEntity> entityTableOneToManys;
    //useGenerator包含多列的时候需要用到
    private List<String> keyProperties;
    private List<String> keyColumns;
    //resultMap对象
    private List<ResultMap> resultMaps;
    //类
    private Class<?> entityClass;

    public EntityTable(Class<?> entityClass) {
        this.entityClass = entityClass;
    }

    public Class<?> getEntityClass() {
        return entityClass;
    }

    public void setTable(Table table) {
        this.name = table.name();
        this.catalog = table.catalog();
        this.schema = table.schema();
    }

    public void setKeyColumns(List<String> keyColumns) {
        this.keyColumns = keyColumns;
    }

    public void setKeyProperties(List<String> keyProperties) {
        this.keyProperties = keyProperties;
    }

    public String getOrderByClause() {
        return orderByClause;
    }

    public void setOrderByClause(String orderByClause) {
        this.orderByClause = orderByClause;
    }

    public String getName() {
    	return name;
    }
    
    public void setName(String name) {
        this.name = name;
    }

    public String getCatalog() {
        return catalog;
    }

    public void setCatalog(String catalog) {
        this.catalog = catalog;
    }

    public String getSchema() {
        return schema;
    }

    public void setSchema(String schema) {
        this.schema = schema;
    }

    public String getBaseSelect() {
        return baseSelect;
    }

    public void setBaseSelect(String baseSelect) {
        this.baseSelect = baseSelect;
    }

    public String getPrefix() {
        if (StringUtil.isNotEmpty(catalog)) {
            return catalog;
        }
        if (StringUtil.isNotEmpty(schema)) {
            return schema;
        }
        return "";
    }

    public List<NestdEntity> getNestdEntitys() {
		List<NestdEntity> list = new ArrayList<NestdEntity>();
		list.addAll(entityTableOneToOnes);
		list.addAll(entityTableOneToManys);
		return Collections.unmodifiableList(list);
	}
    
    public Set<EntityColumn> getEntityClassColumns() {
        return entityClassColumns;
    }

    public void setEntityClassColumns(Set<EntityColumn> entityClassColumns) {
        this.entityClassColumns = entityClassColumns;
    }

    public Set<EntityColumn> getEntityClassPKColumns() {
        return entityClassPKColumns;
    }

    public void setEntityClassPKColumns(Set<EntityColumn> entityClassPKColumns) {
        this.entityClassPKColumns = entityClassPKColumns;
    }
    
	public void setEntityTableOneToOnes(Set<OneToOneEntity> entityTableOneToOnes) {
		this.entityTableOneToOnes = entityTableOneToOnes;
	}

	public void setEntityTableOneToManys(Set<OneToManyEntity> entityTableOneToManys) {
		this.entityTableOneToManys = entityTableOneToManys;
	}

	public Set<OneToOneEntity> getEntityTableOneToOnes() {
		return entityTableOneToOnes;
	}

	public Set<OneToManyEntity> getEntityTableOneToManys() {
		return entityTableOneToManys;
	}

	public String[] getKeyProperties() {
        if (keyProperties != null && keyProperties.size() > 0) {
            return keyProperties.toArray(new String[]{});
        }
        return new String[]{};
    }

    public void setKeyProperties(String keyProperty) {
        if (this.keyProperties == null) {
            this.keyProperties = new ArrayList<String>();
            this.keyProperties.add(keyProperty);
        } else {
            this.keyProperties.add(keyProperty);
        }
    }

    public String[] getKeyColumns() {
        if (keyColumns != null && keyColumns.size() > 0) {
            return keyColumns.toArray(new String[]{});
        }
        return new String[]{};
    }

    public void setKeyColumns(String keyColumn) {
        if (this.keyColumns == null) {
            this.keyColumns = new ArrayList<String>();
            this.keyColumns.add(keyColumn);
        } else {
            this.keyColumns.add(keyColumn);
        }
    }
    
    /**
     * 是否是多表连查 
     * @return
     */
    public boolean hasNestedTableSelect() {
    	return (entityTableOneToOnes != null && entityTableOneToOnes.size() > 0) ||
    			(entityTableOneToManys != null && entityTableOneToManys.size() > 0);
    }
    
    public List<ResultMap> getResultMaps(Configuration configuration, String namespace) {
    	//City => cityMap
		String resultMapId = entityClass.getSimpleName().substring(0, 1).toLowerCase() + entityClass.getSimpleName().substring(1) + "Map";
    	return getResultMaps(configuration, namespace, this, resultMapId);
    }

	/**
     * 生成当前实体的resultMap对象
     *
     * @param configuration
     * @return
     */
    public static List<ResultMap> getResultMaps(Configuration configuration, String namespace, EntityTable entityTable, String resultMapId) {
        if (entityTable.resultMaps != null) {
            return entityTable.resultMaps;
        }
        if (entityTable.entityClassColumns == null || entityTable.entityClassColumns.size() == 0) {
            return null;
        }
        List<ResultMap> resultMaps = __$(configuration, namespace, entityTable, resultMapId, new NestdEntityContext(entityTable.getEntityClass()), true);
        entityTable.resultMaps = resultMaps;
        return entityTable.resultMaps;
    }

	protected static List<ResultMap> __$(Configuration configuration, String namespace, EntityTable entityTable, String resultMapId, NestdEntityContext helper, boolean isRoot) {
		MapperBuilderAssistant builderAssistant = new MapperBuilderAssistant(configuration, "Custom Dynamic Mapper Resources[" + namespace + "]");
    	builderAssistant.setCurrentNamespace(namespace);
		List<ResultMapping> resultMappings = new ArrayList<ResultMapping>();
//		System.out.println("resultMapId:" + resultMapId);
        for (EntityColumn entityColumn : entityTable.entityClassColumns) {
			String column = entityColumn.getColumn();
			if (!helper.isEmpty() || entityTable.hasNestedTableSelect()) {
				column = helper.getAliasSuffix() + "_" + column;
//				System.out.println("column:" + column);
			}
			
            ResultMapping.Builder builder = new ResultMapping.Builder(configuration, entityColumn.getProperty(), column, entityColumn.getJavaType());
            if (entityColumn.getJdbcType() != null) {
                builder.jdbcType(entityColumn.getJdbcType());
            }
            if (entityColumn.getTypeHandler() != null) {
                try {
                    builder.typeHandler(entityColumn.getTypeHandler().newInstance());
                } catch (Exception e) {
                    throw new RuntimeException(e);
                }
            }
            List<ResultFlag> flags = new ArrayList<ResultFlag>();
            if (entityColumn.isId()) {
                flags.add(ResultFlag.ID);
            }
            builder.flags(flags);
            resultMappings.add(builder.build());
        }

        for (NestdEntity nestdEntity : entityTable.getNestdEntitys()) {
        	if(isRoot) {
        		helper.clear();
        	}
        	if(nestdEntity.getEntityTable().hasNestedTableSelect()) {
//        		throw new RuntimeException("多表连查不允许连接表的Entity也属于多表连查.");
        	}
        	helper.record(nestdEntity);
        	
        	//生成的嵌套的resultMapName
        	//格式 tk.mybatis.mapper.mapper.order.TestOrderExtMapper.BaseMapperResultMap_itemsResultMap_dealUserInfoResultMap
        	String nestdEntityResultMapName = resultMapId + "_" + nestdEntity.getProperty() + "ResultMap";
        	//生产嵌套属性对应的数据库字段的别名的前缀
        	List<ResultMap> oneToOneResultMaps = __$(configuration, namespace, nestdEntity.getEntityTable(), nestdEntityResultMapName, helper, false);
        	
        	ResultMapping.Builder builder = new ResultMapping.Builder(configuration, nestdEntity.getProperty(), nestdEntity.getColumn(null), nestdEntity.field.getJavaType());
        	builder.nestedResultMapId(oneToOneResultMaps.get(0).getId());
        	builder.javaType(nestdEntity.field.getJavaType());
        	resultMappings.add(builder.build());
        	
        	helper.clearKeepRoot();
		}
        
        String extend = null;
        Discriminator discriminator = null;
		ResultMapResolver resultMapResolver = new ResultMapResolver(builderAssistant, resultMapId, entityTable.entityClass, extend, discriminator , resultMappings, true);
		
		List<ResultMap> resultMaps = new ArrayList<ResultMap>();
	    try {
	      ResultMap resultMap = resultMapResolver.resolve();
	      resultMaps.add(resultMap);
	      
	      /**
	       * debug
	       */
	      logger.debug("resultMaps:{} println============", resultMap.getId());
	      List<ResultMapping> mappings = resultMap.getResultMappings();
	      for (ResultMapping resultMapping : mappings) {
			logger.debug("resultMapping:{}={}-{}", new Object[]{resultMapping.getProperty(), resultMapping.getColumn(), resultMapping.getColumnPrefix()});
	      }
	    } catch (IncompleteElementException  e) {
	      configuration.addIncompleteResultMap(resultMapResolver);
	      throw e;
	    }
		return resultMaps;
	}
}
